package com.authine.cloudpivot.ext.service.impl;

import cn.hutool.core.codec.Base64;
import cn.hutool.core.map.MapUtil;
import com.alibaba.cola.dto.SingleResponse;
import com.alibaba.cola.exception.BizException;
import com.alibaba.fastjson.JSON;
import com.authine.cloudpivot.ext.constants.AppConst;
import com.authine.cloudpivot.ext.domain.jizhong.common.BsscListenerEnum;
import com.authine.cloudpivot.ext.domain.jizhong.model.*;
import com.authine.cloudpivot.ext.domain.jizhong.vo.BsscOrderReceivedVo;
import com.authine.cloudpivot.ext.domain.jizhong.vo.BsscOrderVo;
import com.authine.cloudpivot.ext.domain.query.MallQuery;
import com.authine.cloudpivot.ext.dto.GatewayParam;
import com.authine.cloudpivot.ext.dto.system.OutApiClientDto;
import com.authine.cloudpivot.ext.model.bosi.*;
import com.authine.cloudpivot.ext.model.goods.GoodsModel;
import com.authine.cloudpivot.ext.model.goods.MallGoodsModel;
import com.authine.cloudpivot.ext.service.BsscService;
import com.authine.cloudpivot.ext.service.GoodsService;
import com.authine.cloudpivot.ext.utils.AppUrl;
import com.authine.cloudpivot.ext.utils.BigDecimalUtils;
import com.authine.cloudpivot.ext.utils.StringUtils;
import com.authine.cloudpivot.ext.utils.system.OutApiClientApiUtils;
import com.authine.mvp.app.launcher.domain.AttachmentFormat;
import com.authine.mvp.app.launcher.domain.utills.ApplicationContextUtils;
import com.bssc.supplier.sdk.BsscClient;
import com.bssc.supplier.sdk.BsscClientParams;
import com.bssc.supplier.sdk.aftersale.reject.BsscAfterSaleRejectReq;
import com.bssc.supplier.sdk.aftersale.reject.BsscAfterSaleRejectResp;
import com.bssc.supplier.sdk.aftersale.reject.BsscAfterSaleRejectWrap;
import com.bssc.supplier.sdk.goods.detail.BsscGoodsDetailReq;
import com.bssc.supplier.sdk.goods.detail.BsscGoodsDetailResp;
import com.bssc.supplier.sdk.goods.detail.BsscGoodsDetailWrap;
import com.bssc.supplier.sdk.goods.detail.entity.GoodsDetail;
import com.bssc.supplier.sdk.goods.imgs.BsscGoodsImgReq;
import com.bssc.supplier.sdk.goods.imgs.BsscGoodsImgResp;
import com.bssc.supplier.sdk.goods.imgs.BsscGoodsImgWrap;
import com.bssc.supplier.sdk.goods.imgs.entity.GoodsImg;
import com.bssc.supplier.sdk.goods.imports.BsscGoodsImportReq;
import com.bssc.supplier.sdk.goods.imports.BsscGoodsImportResp;
import com.bssc.supplier.sdk.goods.imports.BsscGoodsImportWrap;
import com.bssc.supplier.sdk.goods.imports.entity.GoodsImport;
import com.bssc.supplier.sdk.goods.price.BsscGoodsPriceReq;
import com.bssc.supplier.sdk.goods.price.BsscGoodsPriceResp;
import com.bssc.supplier.sdk.goods.price.BsscGoodsPriceWrap;
import com.bssc.supplier.sdk.goods.price.entity.GoodsPrice;
import com.bssc.supplier.sdk.goods.properties.BsscGoodsPropertyReq;
import com.bssc.supplier.sdk.goods.properties.BsscGoodsPropertyResp;
import com.bssc.supplier.sdk.goods.properties.BsscGoodsPropertyWrap;
import com.bssc.supplier.sdk.goods.properties.entity.GoodsProperty;
import com.bssc.supplier.sdk.goods.status.BsscGoodsStatusReq;
import com.bssc.supplier.sdk.goods.status.BsscGoodsStatusResp;
import com.bssc.supplier.sdk.goods.status.BsscGoodsStatusWrap;
import com.bssc.supplier.sdk.goods.status.entity.GoodsStatus;
import com.bssc.supplier.sdk.goods.stock.BsscGoodsStockReq;
import com.bssc.supplier.sdk.goods.stock.BsscGoodsStockResp;
import com.bssc.supplier.sdk.goods.stock.BsscGoodsStockWrap;
import com.bssc.supplier.sdk.goods.stock.entity.GoodsStock;
import com.bssc.supplier.sdk.order.comfirm.BsscOrderConfirmReq;
import com.bssc.supplier.sdk.order.comfirm.BsscOrderConfirmResp;
import com.bssc.supplier.sdk.order.comfirm.BsscOrderConfirmWrap;
import com.bssc.supplier.sdk.order.deliver.BsscOrderDeliverReq;
import com.bssc.supplier.sdk.order.deliver.BsscOrderDeliverResp;
import com.bssc.supplier.sdk.order.deliver.BsscOrderDeliverWrap;
import com.bssc.supplier.sdk.order.detail.BsscOrderDetailReq;
import com.bssc.supplier.sdk.order.detail.BsscOrderDetailResp;
import com.bssc.supplier.sdk.order.detail.BsscOrderDetailWrap;
import com.bssc.supplier.sdk.order.notice.BsscOrderDeliveredNoticeReq;
import com.bssc.supplier.sdk.order.notice.BsscOrderDeliveredNoticeResp;
import com.bssc.supplier.sdk.order.notice.BsscOrderDeliveredNoticeWrap;
import com.bssc.supplier.sdk.order.outgoing.BsscOrderOutgoingReq;
import com.bssc.supplier.sdk.order.outgoing.BsscOrderOutgoingResp;
import com.bssc.supplier.sdk.order.outgoing.BsscOrderOutgoingWrap;
import com.bssc.supplier.sdk.order.outgoing.entity.OutgoingListEntity;
import com.bssc.supplier.sdk.util.JsonUtils;
import com.bssc.supplier.sdk.util.SignatureUtils;
import com.fasterxml.jackson.databind.JsonNode;
import com.fasterxml.jackson.databind.ObjectMapper;
import lombok.SneakyThrows;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.collections4.MapUtils;
import org.bouncycastle.jce.provider.BouncyCastleProvider;
import org.springframework.beans.BeanUtils;
import org.springframework.boot.json.JacksonJsonParser;
import org.springframework.http.HttpEntity;
import org.springframework.http.HttpHeaders;
import org.springframework.http.MediaType;
import org.springframework.util.LinkedMultiValueMap;
import org.springframework.util.MultiValueMap;
import org.springframework.util.ObjectUtils;
import org.springframework.web.client.RestTemplate;

import java.math.BigDecimal;
import java.security.Security;
import java.util.*;
import java.util.stream.Collectors;

/**
 * @Author hxd
 * @Date 2021/9/27 14:47
 * @Description 冀中电商对接业务
 **/
@Slf4j
public class BsscServiceImpl implements BsscService {
    private final static String PRIVATE_KEY = "privateKey";
    private final static String PUBLIC_EC_KEY = "publicEcKey";
    private final static String PUBLIC_EA_KEY = "publicEaKey";

    private final ObjectMapper objectMapper = new ObjectMapper();
    private final RestTemplate restTemplate = ApplicationContextUtils.getBean(RestTemplate.class);
    private String profile = System.getProperty("spring.profiles.active", "debug");
    private GoodsService goodsService = GoodsServiceImpl.getInstance();

    /**
     * 转换图片字符串格式
     *
     * @param images
     * @return
     */
    public static String convertImages(List<AttachmentFormat> images) {
        ///api/file/download?refId=be5a1d4ee929497bbccb8b772357aebd

        final String domain = "";

        String result = "";
        if (!ObjectUtils.isEmpty(images)) {
            result = images.stream().map(a -> domain + "/api/file/download?refId=" + a.getId()).collect(Collectors.joining(","));
        }

        return "[" + result + "]";
    }

    public static BsscServiceImpl getInstance() {
        return BsscServiceBuilder.instance;
    }

    /**
     * 消息监听
     *
     * @param bsscReq
     * @return
     */
    @SneakyThrows
    public BsscResp messageListening(BsscReq<String> bsscReq) {

        log.warn("bsscReq:{}", objectMapper.writeValueAsString(bsscReq));
        // 检查认证信息
        try {
            checkToken(bsscReq.getAccessToken());
        } catch (Exception e) {
            return BsscResp.invalid("token");
        }

        Map<String, String> clientSecret = this.getClientSecret();

        // 过滤sign
        BsscReq<String> bssc = new BsscReq<>();
        BeanUtils.copyProperties(bsscReq, bssc);
        bssc.setSign(null);

        // 验签
        boolean verify = SignatureUtils.verify(JSON.toJSONString(bssc), bsscReq.getSign(), clientSecret.get(PUBLIC_EA_KEY));
        if (!verify) {
            return BsscResp.invalid("sign");
        }

        // 解码data
        String jsonData = JsonUtils.toJsonNoCode(bsscReq.getData());
        String data = Base64.decodeStr(jsonData);
        log.warn("data:{}", data);

        // 接收监听消息体
        ListenerModel listenerModel = objectMapper.readValue(data, ListenerModel.class);
        listenerModel.setAccessToken(bsscReq.getAccessToken());
        // 消息内容
        log.warn("listener-data:{}、{}、{}、{}", listenerModel.getId(), listenerModel.getType(), listenerModel.getContent(), listenerModel.getTime());
        // 根据请求的消息类型 做出相应的业务调用
        return this.businessProcessing(listenerModel, clientSecret);
    }

    /**
     * 冀中认证
     *
     * @param bsscReq
     * @return
     */
    @SneakyThrows
    public BsscResp getAuth(BsscReq<String> bsscReq) {


        Map<String, String> clientSecret = this.getClientSecret();


        // 过滤sign
        BsscReqModel<String> bssc = new BsscReqModel<>();
        BeanUtils.copyProperties(bsscReq, bssc);
        bssc.setSign(null);
        if (Security.getProvider(BouncyCastleProvider.PROVIDER_NAME) == null) {
            Security.addProvider(new BouncyCastleProvider());
        }
        // 验签
        boolean verify = SignatureUtils.verify(JSON.toJSONString(bssc), bsscReq.getSign(), clientSecret.get(PUBLIC_EA_KEY));
        if (!verify) {
            return BsscResp.invalid("sign");
        }


        // data
        String jsonData = JsonUtils.toJsonNoCode(bsscReq.getData());
        String data = Base64.decodeStr(jsonData);
        log.warn("data:{}", data);
        bsscReq.setData(data);


        // 获取token 验证
        String token = getToken(bsscReq);
        log.warn("token:{}", token);
        if (null == token) {
            return BsscResp.invalid("token");
        }
        JsonNode jsonNode = objectMapper.readTree(token);
        String accessToken = jsonNode.get("access_token").toString().replace("\"", "");
        String expiresIn = jsonNode.get("expires_in").toString().replace("\"", "");
        log.warn("accessToken:{}", accessToken);
        log.warn("expiresIn:{}", expiresIn);


        Map<String, String> map = new HashMap<>(2);
        map.put("accessToken", accessToken);
        map.put("expiresIn", expiresIn);
        String rspJsonData = JsonUtils.toJsonNoCode(map);
        String respData = Base64.encode(rspJsonData);
        log.warn("respData:{}", respData);

        // sign 加签
        BsscResp bsscResp = new BsscResp("0", "调用成功", respData, null);
        byte[] signReq = SignatureUtils.sign(JSON.toJSONString(bsscResp), clientSecret.get(PRIVATE_KEY));
        String sign = Base64.encode(signReq);
        log.warn("sign:{}", sign);
        bsscResp.setSign(sign);

        return bsscResp;
    }

    /**
     * 获取品类列表
     *
     * @param bsscReq
     * @return
     */
    @SneakyThrows
    public BsscResp getItemList(BsscReq<String> bsscReq) {

        Map<String, String> clientSecret = this.getClientSecret();

        // 检查认证信息
        try {
            checkToken(bsscReq.getAccessToken());
        } catch (Exception e) {
            return BsscResp.invalid("token");
        }

        // 过滤sign
        BsscReq<String> bssc = new BsscReq<>();
        BeanUtils.copyProperties(bsscReq, bssc);
        bssc.setSign(null);

        // 验签
        boolean verify = SignatureUtils.verify(JSON.toJSONString(bssc), bsscReq.getSign(), clientSecret.get(PUBLIC_EA_KEY));
        if (!verify) {
            return BsscResp.invalid("sign");
        }
        // 商品品类 固定
        Map<String, Object> map = new HashMap<>(1);
        List<GoodsCatalogs> catalogsList;
        if ("product".equals(profile)) {
            catalogsList = GoodsCatalogs.Catalogs();
        } else {
            catalogsList = GoodsCatalogs.TestCatalogs();
        }
        map.put("catalogs", catalogsList);
        String rspJsonData = JsonUtils.toJsonNoCode(map);
        String respData = Base64.encode(rspJsonData);
        log.warn("respData:{}", respData);
        // sign 加签
        BsscResp bsscResp = new BsscResp("0", "调用成功", respData, null);
        byte[] signReq = SignatureUtils.sign(JSON.toJSONString(bsscResp), clientSecret.get(PRIVATE_KEY));
        String sign = Base64.encode(signReq);
        log.warn("sign:{}", sign);
        bsscResp.setSign(sign);

        return bsscResp;
    }

    /**
     * 查询商品库存
     *
     * @param bsscReq
     * @return
     */
    @SneakyThrows
    public BsscResp getGoodsInventory(BsscReq<String> bsscReq) {

        // 检查认证信息
        try {
            checkToken(bsscReq.getAccessToken());
        } catch (Exception e) {
            return BsscResp.invalid("token");
        }

        // 过滤sign
        BsscReq<String> bssc = new BsscReq<>();
        BeanUtils.copyProperties(bsscReq, bssc);
        bssc.setSign(null);

        Map<String, String> clientSecret = this.getClientSecret();

        // 验签
        boolean verify = SignatureUtils.verify(JSON.toJSONString(bssc), bsscReq.getSign(), clientSecret.get(PUBLIC_EA_KEY));
        if (!verify) {
            return BsscResp.invalid("sign");
        }

        // 解码data
        String jsonData = JsonUtils.toJsonNoCode(bsscReq.getData());
        String data = Base64.decodeStr(jsonData);
        log.warn("getGoodsInventory--data:{}", data);
        BsscGoodsImportReq dataReq = objectMapper.readValue(data, BsscGoodsImportReq.class);

        String goodsIds = dataReq.getGoods().stream().map(GoodsImport::getGoodsId).collect(Collectors.joining(" "));

        // 拿到请求信息请求goodsApi
        MallGoodsModel mallGoodsModel = goodsService.pageMallFullGoods(MallQuery.builder().goodsId(goodsIds).build());
        List<GoodsStock> goodsStockList = new ArrayList<>();
        mallGoodsModel.getGoods().forEach(t -> {
            GoodsStock goodsStock = new GoodsStock();
            goodsStock.setGoodsId(String.valueOf(t.getId()));
            goodsStock.setAreaId("");
            // 1有货
            goodsStock.setStockState(1);
            goodsStock.setStockStateDesc("");
            goodsStock.setRemainNum(t.getStock() == null ? 1000 : t.getStock().intValue());
            goodsStockList.add(goodsStock);
        });
        GoodsStockModel stockModel = GoodsStockModel.builder().stocks(goodsStockList).build();

        // 返回信息包装成bssc编码加密返回
        String rspJsonData = JsonUtils.toJsonNoCode(stockModel);
        String respData = Base64.encode(rspJsonData);
        // sign 加签
        BsscResp bsscResp = new BsscResp("0", "调用成功", respData, null);

        byte[] signReq = SignatureUtils.sign(JSON.toJSONString(bsscResp), clientSecret.get(PRIVATE_KEY));
        String sign = Base64.encode(signReq);
        bsscResp.setSign(sign);

        return bsscResp;
    }

    /**
     * 查询商品金额
     *
     * @return
     */
    @SneakyThrows
    public BsscResp getGoodsPrice(BsscReq<String> bsscReq) {
        // 检查认证信息
        try {
            checkToken(bsscReq.getAccessToken());
        } catch (Exception e) {
            return BsscResp.invalid("token");
        }

        // 过滤sign
        BsscReq<String> bssc = new BsscReq<>();
        BeanUtils.copyProperties(bsscReq, bssc);
        bssc.setSign(null);

        Map<String, String> clientSecret = this.getClientSecret();

        // 验签
        boolean verify = SignatureUtils.verify(JSON.toJSONString(bssc), bsscReq.getSign(), clientSecret.get(PUBLIC_EA_KEY));
        if (!verify) {
            return BsscResp.invalid("sign");
        }

        // 解码data
        String jsonData = JsonUtils.toJsonNoCode(bsscReq.getData());
        String data = Base64.decodeStr(jsonData);
        log.warn("getGoodsPrice--data:{}", data);
        GoodsPricesModel dataReq = objectMapper.readValue(data, GoodsPricesModel.class);

        List<String> result = Arrays.asList(dataReq.getGoodsIds().split(","));

        String goodsIds = result.stream().collect(Collectors.joining(" "));

        MallGoodsModel mallGoodsModel = goodsService.pageMallFullGoods(MallQuery.builder().goodsId(goodsIds).build());

        List<GoodsPrice> goodsPriceList = new ArrayList<>();
        mallGoodsModel.getGoods().forEach(t -> {
            GoodsPrice goodsPrice = new GoodsPrice();
            goodsPrice.setGoodsId(t.getId().toString());
            goodsPrice.setDsPrice(BigDecimalUtils.round(BigDecimalUtils.mul(new BigDecimal(t.getPretaxPrice()), new BigDecimal((1 + t.getTaxRate()))), 2));
            goodsPrice.setPrice(BigDecimalUtils.round(BigDecimalUtils.mul(new BigDecimal(t.getPretaxPrice()), new BigDecimal((1 + t.getTaxRate()))), 2));
            goodsPrice.setTaxFreePrice(BigDecimal.valueOf(t.getPretaxPrice()));
            goodsPriceList.add(goodsPrice);
        });
        GoodsPriceModel goodsPriceModel = GoodsPriceModel.builder().prices(goodsPriceList).build();

        // 返回信息包装成bssc编码加密返回
        String rspJsonData = JsonUtils.toJsonNoCode(goodsPriceModel);
        String respData = Base64.encode(rspJsonData);
        // sign 加签
        BsscResp bsscResp = new BsscResp("0", "调用成功", respData, null);

        byte[] signReq = SignatureUtils.sign(JSON.toJSONString(bsscResp), clientSecret.get(PRIVATE_KEY));
        String sign = Base64.encode(signReq);
        bsscResp.setSign(sign);

        return bsscResp;
    }

    /**
     * 查询物流
     *
     * @param bsscReq
     * @return
     */
    @SneakyThrows
    public BsscResp getLogisticsInformation(BsscReq<String> bsscReq) {
        // 检查认证信息
        try {
            checkToken(bsscReq.getAccessToken());
        } catch (Exception e) {
            return BsscResp.invalid("token");
        }

        // 过滤sign
        BsscReq<String> bssc = new BsscReq<>();
        BeanUtils.copyProperties(bsscReq, bssc);
        bssc.setSign(null);

        Map<String, String> clientSecret = this.getClientSecret();

        // 验签
        boolean verify = SignatureUtils.verify(JSON.toJSONString(bssc), bsscReq.getSign(), clientSecret.get(PUBLIC_EA_KEY));
        if (!verify) {
            return BsscResp.invalid("sign");
        }

        // 解码data
        String jsonData = JsonUtils.toJsonNoCode(bsscReq.getData());
        String data = Base64.decodeStr(jsonData);
        log.warn("getLogisticsInformation--data:{}", data);
        // 请求data
        LogisticsInformationRequest dataReq = objectMapper.readValue(data, LogisticsInformationRequest.class);

        /*// 调用查询物流接口
        RestTemplate restTemplate = new RestTemplate();
        HttpHeaders headers = new HttpHeaders();
        headers.setContentType(MediaType.APPLICATION_FORM_URLENCODED);
        headers.add("Authorization", "Bearer " + bsscReq.getAccessToken());

        Map<String, String> map = new HashMap<>();
        map.put("newOrderGoodsIds", dataReq.getOutgoingCode());
        ResponseEntity<String> s = restTemplate.exchange("http://api-v1/v1/order/customer/goods/delivery?newOrderGoodsIds={newOrderGoodsIds}", HttpMethod.GET, new HttpEntity<>(headers), String.class, map);
        // 物流单号
        JsonNode jsonNode = objectMapper.readTree(s.getBody());
        String waybill = jsonNode.get("data").get(0).get("waybill").toString().replace("\"", "");
        String expressCode = waybill;
        // 物流公司
        JsonNode jsonNodeExpressCompanyName = objectMapper.readTree(s.getBody());
        String expressCompanyNameStr = jsonNodeExpressCompanyName.get("data").get(0).get("logistics").toString().replace("\"", "");
        String expressCompanyName = expressCompanyNameStr;
        Map<String, String> mmp = new HashMap<>();
        mmp.put("waybills", waybill);
        ResponseEntity<String> q = restTemplate.exchange("http://api-v1/v1/order/customer/logistics-detail?waybills={waybills}", HttpMethod.GET, new HttpEntity<>(headers), String.class, mmp);
        // 物流
        JsonNode jsonNodeOrderDetail = objectMapper.readTree(q.getBody());
        String jsonNodeDetailStr = jsonNodeOrderDetail.get("data").get(0).toString();
        ObjectMapper objectMapper = new ObjectMapper();
        ApiLogisticsInfo apiLogisticsInfo = objectMapper.readValue(jsonNodeDetailStr, ApiLogisticsInfo.class);

        List<DeliveryTrack> deliveryTrackList = new ArrayList<>();
        for (ApiLogisticsInfoDetail detail : apiLogisticsInfo.getDetails()) {
            DeliveryTrack deliveryTrack = DeliveryTrack.builder().expressDetail(detail.getContext()).expressTime(detail.getTime()).optName("").build();
            deliveryTrackList.add(deliveryTrack);
        }

        // 调用订单查询物流接口，返回信息封装
        LogisticsInformationResult logisticsInformationResult = LogisticsInformationResult.builder().expressCompanyName(expressCompanyName).expressCode(expressCode).deliveryTrack(deliveryTrackList).build();

        // 返回信息包装成bssc编码加密返回
        String rspJsonData = JsonUtils.toJsonNoCode("{}");*/
        String respData = Base64.encode("{}");
        // sign 加签
        BsscResp bsscResp = new BsscResp("0", "调用成功", respData, null);

        byte[] signReq = SignatureUtils.sign(JSON.toJSONString(bsscResp), clientSecret.get(PRIVATE_KEY));
        String sign = Base64.encode(signReq);
        bsscResp.setSign(sign);

        return bsscResp;
    }

    /**
     * 查询订单系统订单号
     *
     * @param bsscReq
     * @return
     */
    @SneakyThrows
    public BsscResp getOrderId(BsscReq<String> bsscReq) {
        //客户未实现

        BsscResp bsscResp = new BsscResp("0", "调用成功", null, null);
        Map<String, String> clientSecret = this.getClientSecret();
        byte[] signReq = SignatureUtils.sign(JSON.toJSONString(bsscResp), clientSecret.get(PRIVATE_KEY));
        String sign = Base64.encode(signReq);
        bsscResp.setSign(sign);

        return bsscResp;
    }

    /**
     * 查询电商系统售后单号
     *
     * @param bsscReq
     * @return
     */
    @SneakyThrows
    public BsscResp getMallAfterSaleNo(BsscReq<String> bsscReq) {
        //客户未实现

        BsscResp bsscResp = new BsscResp("0", "调用成功", null, null);
        Map<String, String> clientSecret = this.getClientSecret();
        byte[] signReq = SignatureUtils.sign(JSON.toJSONString(bsscResp), clientSecret.get(PRIVATE_KEY));
        String sign = Base64.encode(signReq);
        bsscResp.setSign(sign);

        return bsscResp;
    }

    /**
     * 导入商品
     *
     * @param goodsModelList
     * @return
     */
    public BsscResp goodsImport(final List<GoodsModel> goodsModelList) {
        // 固买商品信息-->冀中商品信息
        BsscGoodsImportReq bsscGoodsImportReq = new BsscGoodsImportReq();
        List<GoodsImport> goodsImports = new ArrayList<>();
        for (GoodsModel goods : goodsModelList) {
            // 创建请求对象
            GoodsImport goodsImport = new GoodsImport();
            // 商品sku，每个商品SKU必须唯一。
            goodsImport.setGoodsId(String.valueOf(goods.getId()));
            // 从固定品目取冀中品目相关信息
            List<GoodsCatalogs> goodsCatalogsList;
            if ("product".equals(profile)) {
                goodsCatalogsList = GoodsCatalogs.Catalogs();
            } else {
                goodsCatalogsList = GoodsCatalogs.TestCatalogs();
            }
            Optional<GoodsCatalogs> first = goodsCatalogsList.stream().filter(g -> g.getName().equals(goods.getCatalog())).findFirst();
            if (first.isPresent()) {
                // 电商品目ID
                goodsImport.setCatalogId(first.get().getId());
                // 电商品目名称
                goodsImport.setCatalogName(first.get().getName());
                // 标准品目ID，仅限数字。
                goodsImport.setStandardCatalogId(first.get().getStandardCatalog().getStandardCatalogId());
                // 标准品目名称。
                goodsImport.setStandardCatalogName(first.get().getStandardCatalog().getStandardCatalogName());
            }
            // 品牌名称（中文），若为空，则英文品牌必填
            goodsImport.setBrandName(goods.getBrand());
            // 品牌名称（英文），若为空，则中文品牌必填
            // goodsImport.setBrandNameEn("");
            // 商品条形码 -- 非必填
            goodsImport.setUpc(goods.getBar_code());
            // 商品名称
            goodsImport.setName(goods.getName() + " - " + goods.getModel());
            // 电商价格。单位元，最多精确到分。
            goodsImport.setDsPrice(BigDecimalUtils.round(goods.getPretax_price(), 2));
            // 协议价格。单位元，最多精确到分。
            goodsImport.setPrice(BigDecimalUtils.round(goods.getPretax_price(), 2));
            // 计量单位
            goodsImport.setUnit(goods.getUnit());
            // 库存数量
            goodsImport.setStock(goods.getStock() == null ? 1000 : goods.getStock().intValue());
            // 产地 -- 非必填
            goodsImport.setGoodsPlace(goods.getPlace());
            // 生产日期，格式YYYYMMDD -- 非必填
            // goodsImport.setGoodsDate("");
            // 包装清单 -- 非必填
            // goodsImport.setPacking("");
            // 商品官网链接 -- 非必填
            // goodsImport.setGoodsUrl("");
            // 商品轮播图，JSON格式，其中第一张为主图。如["imgUrl1","imgUrl2"]
            goodsImport.setBarImgUrls(convertImages(goods.getImages()));

            // 商品的规格，JSON格式，该json需按照品目模板填写。如：{"key1":"value1","key2":"value2","key3":"value31|value32"}
            goodsImport.setProperties("{\"规格\":\"" + goods.getSpec() + "\"}");
            // 商品介绍
            goodsImport.setDescription(goods.getName());
            // 货品交货日期（单位：天，向上取整）。如果填3，则指的是3天内交货 -- 非必填
            goodsImport.setDeliveryPeriod(Optional.ofNullable(goods.getDelivery()).orElse(BigDecimal.ZERO).intValue());
            // 最小起定量 -- 非必填
            goodsImport.setMoq(goods.getMin_order());
            // 未税价 -- 非必填
            goodsImport.setTaxFreePrice(goods.getPrice());
            // 是否自营（0:非自营 ，1：自营）
            goodsImport.setIsSelfOperated(1);
            // 是否支持无库存下单（0:不支持 ，1：支持） -- 非必填
            goodsImport.setIsOversold(1);
            // 商品重量 非必填
            // goodsImport.setWeight(null != goods.getWeight() ? goods.getWeight().toString() : "");
            // 是否自行配送（0:非自行配送 ，1：自行配送） -- 非必填
            goodsImport.setIsSelfOperated(1);
            // 商品状态(0下架 1上架 非必填，不填默认为上架)
            goodsImport.setStatus(1);

            goodsImports.add(goodsImport);

        }
        bsscGoodsImportReq.setAccount("jzny");
        bsscGoodsImportReq.setGoods(goodsImports);
        //创建请求包装类
        BsscGoodsImportWrap bsscGoodsImportWrap = new BsscGoodsImportWrap(bsscGoodsImportReq);
        BsscGoodsImportResp execute = getBsscClient().execute(bsscGoodsImportWrap);

        log.warn("导入商品-request:{}", bsscGoodsImportReq);
        log.warn("导入商品-response:{}", execute);
        BsscResp bsscResp = new BsscResp();
        BeanUtils.copyProperties(execute, bsscResp);
        return bsscResp;
    }

    /**
     * 更新商品金额
     *
     * @param goodsModel
     * @return
     */
    @Override
    public BsscResp updateGoodsAmount(final GoodsModel goodsModel) {
        //创建请求对象
        BsscGoodsPriceReq bsscGoodsPriceReq = new BsscGoodsPriceReq();
        List<GoodsPrice> goodsPrices = new ArrayList<>();
        GoodsPrice goodsPrice = new GoodsPrice();
        // 商品sku
        goodsPrice.setGoodsId(String.valueOf(goodsModel.getId()));
        // 电商价格。单位元，最多精确到分。
        goodsPrice.setDsPrice(BigDecimalUtils.round(goodsModel.getPretax_price(), 2));
        // 协议价格。单位元，最多精确到分。
        goodsPrice.setPrice(BigDecimalUtils.round(goodsModel.getPretax_price(), 2));
        // 未税价。单位元，最多精确到分。不传则认为不更改
        goodsPrice.setTaxFreePrice(goodsModel.getPrice());

        goodsPrices.add(goodsPrice);
        bsscGoodsPriceReq.setAccount("jzny");
        bsscGoodsPriceReq.setGoods(goodsPrices);
        //创建包装类
        BsscGoodsPriceWrap bsscGoodsPriceWrap = new BsscGoodsPriceWrap(bsscGoodsPriceReq);
        //发起请求
        BsscGoodsPriceResp bsscGoodsPriceResp = getBsscClient().execute(bsscGoodsPriceWrap);
        log.warn("更新商品金额-request:{}", bsscGoodsPriceWrap);
        log.warn("更新商品金额-response:{}", bsscGoodsPriceResp);
        BsscResp bsscResp = new BsscResp();
        BeanUtils.copyProperties(bsscGoodsPriceResp, bsscResp);
        return bsscResp;
    }

    /**
     * 库存变更
     */
    @Override
    public BsscResp updateGoodsInventory(final GoodsModel goodsModel) {
        //创建请求对象
        BsscGoodsStockReq req = new BsscGoodsStockReq();
        List<GoodsStock> goodsStocks = new ArrayList<>();
        GoodsStock goodsStock = new GoodsStock();
        goodsStock.setGoodsId(String.valueOf(goodsModel.getId()));
        goodsStock.setAreaId("6666");
        goodsStock.setRemainNum(33);
        goodsStock.setStockState(1);
        goodsStock.setStockStateDesc("pp");
        goodsStocks.add(goodsStock);
        req.setAccount("test");
        req.setStocks(goodsStocks);
        //创建包装类
        BsscGoodsStockWrap wrap = new BsscGoodsStockWrap(req);
        //发起请求
        BsscGoodsStockResp resp = getBsscClient().execute(wrap);
        log.warn("request:{}", wrap);
        log.warn("response:{}", resp);
        BsscResp bsscResp = new BsscResp();
        BeanUtils.copyProperties(resp, bsscResp);
        return bsscResp;
    }

    @Override
    public BsscResp updateGoodsStatus(final List<GoodsModel> goodsModel) {
        //创建请求对象
        BsscGoodsStatusReq bsscGoodsStatusReq = new BsscGoodsStatusReq();
        List<GoodsStatus> goodsStatuses = new ArrayList<>();
        goodsModel.forEach(goods -> {
            GoodsStatus goodsStatus = new GoodsStatus();
            goodsStatus.setGoodsId(String.valueOf(goods.getId()));
            // 上下架状态：1上架 0下架
            goodsStatus.setStatus(goods.getMall_sales() ? 1 : 0);
            goodsStatuses.add(goodsStatus);
        });
        bsscGoodsStatusReq.setAccount("jzny");
        bsscGoodsStatusReq.setGoods(goodsStatuses);
        // 创建包装类
        BsscGoodsStatusWrap bsscGoodsStatusWrap = new BsscGoodsStatusWrap(bsscGoodsStatusReq);
        // 发起请求
        BsscGoodsStatusResp bsscGoodsStatusResp = getBsscClient().execute(bsscGoodsStatusWrap);
        log.warn("上下架变更-request:{}", bsscGoodsStatusWrap);
        log.warn("上下架变更-response:{}", bsscGoodsStatusResp);
        BsscResp bsscResp = new BsscResp();
        BeanUtils.copyProperties(bsscGoodsStatusResp, bsscResp);
        return bsscResp;
    }

    @Override
    public BsscResp updateGoodsImages(final GoodsModel goodsModel) {
        // 创建请求对象
        BsscGoodsImgReq bsscGoodsImgReq = new BsscGoodsImgReq();
        List<GoodsImg> goodsImgList = new ArrayList<>();
        GoodsImg goodsImg = new GoodsImg();
        goodsImg.setGoodsId(String.valueOf(goodsModel.getId()));
        goodsImg.setBarImgUrls(convertImages(goodsModel.getImages()));
        goodsImgList.add(goodsImg);
        bsscGoodsImgReq.setAccount("jzny");
        bsscGoodsImgReq.setGoods(goodsImgList);
        // 创建包装类
        BsscGoodsImgWrap bsscGoodsImgWrap = new BsscGoodsImgWrap(bsscGoodsImgReq);
        // 发起请求
        BsscGoodsImgResp bsscGoodsImgResp = getBsscClient().execute(bsscGoodsImgWrap);
        log.warn("图片变更-request:{}", bsscGoodsImgWrap);
        log.warn("图片变更-response:{}", bsscGoodsImgResp);
        BsscResp bsscResp = new BsscResp();
        BeanUtils.copyProperties(bsscGoodsImgResp, bsscResp);
        return bsscResp;
    }

    @Override
    public BsscResp updateGoodsSpec(final GoodsModel goodsModel) {
        // 创建请求对象
        BsscGoodsPropertyReq bsscGoodsPropertyReq = new BsscGoodsPropertyReq();
        List<GoodsProperty> goodsProperties = new ArrayList<>();
        GoodsProperty goodsProperty = new GoodsProperty();
        goodsProperty.setGoodsId(String.valueOf(goodsModel.getId()));
        goodsProperty.setProperties("{\"规格\":\"" + goodsModel.getModel() + "\"}");
        goodsProperties.add(goodsProperty);
        bsscGoodsPropertyReq.setAccount("jzny");
        bsscGoodsPropertyReq.setGoods(goodsProperties);
        // 创建包装类
        BsscGoodsPropertyWrap bsscGoodsPriceWrap = new BsscGoodsPropertyWrap(bsscGoodsPropertyReq);
        // 发起请求
        BsscGoodsPropertyResp bsscGoodsPropertyResp = getBsscClient().execute(bsscGoodsPriceWrap);
        log.warn("规格变更-request:{}", bsscGoodsPriceWrap);
        log.warn("规格变更-response:{}", bsscGoodsPropertyResp);
        BsscResp bsscResp = new BsscResp();
        BeanUtils.copyProperties(bsscGoodsPropertyResp, bsscResp);
        return bsscResp;
    }

    @Override
    public BsscResp updateGoodsDetail(final GoodsModel goodsModel) {

        // 创建请求对象
        GoodsDetail goodsDetail = new GoodsDetail();

        // 商品SKU
        goodsDetail.setGoodsId(String.valueOf(goodsModel.getId()));
        // 商品名称
        goodsDetail.setName(goodsModel.getName());
        // 商品条形码
        goodsDetail.setUpc(goodsModel.getUnspsc());
        // 产地
        goodsDetail.setGoodsPlace(goodsModel.getPlace());
        // 生产日期
        goodsDetail.setGoodsDate("");
        // 产品简介
        goodsDetail.setDescription(goodsModel.getDescription());
        // 品牌名称
        goodsDetail.setBrandName(goodsModel.getBrand());

        // 从固定品目取冀中品目相关信息
        List<GoodsCatalogs> goodsCatalogsList;
        if ("product".equals(profile)) {
            goodsCatalogsList = GoodsCatalogs.Catalogs();
        } else {
            goodsCatalogsList = GoodsCatalogs.TestCatalogs();
        }
        Optional<GoodsCatalogs> first = goodsCatalogsList.stream().filter(g -> g.getName().equals(goodsModel.getCatalog())).findFirst();
        if (first.isPresent()) {
            // 电商品目ID
            goodsDetail.setCatalogId(first.get().getId());
            // 电商品目名称
            goodsDetail.setCatalogName(first.get().getName());
            // 标准品目ID，仅限数字。
            goodsDetail.setStandardCatalogId(first.get().getStandardCatalog().getStandardCatalogId());
            // 标准品目名称。
            goodsDetail.setStandardCatalogName(first.get().getStandardCatalog().getStandardCatalogName());
        }
        // 计量单位
        goodsDetail.setUnit(goodsModel.getUnit());
        // 包装清单
        goodsDetail.setPacking(goodsModel.getPackaging());
        // 货品交货日期
        goodsDetail.setDeliveryPeriod(Optional.ofNullable(goodsModel.getDelivery()).orElse(BigDecimal.ZERO).intValue());
        // 最小起订量
        goodsDetail.setMoq(goodsModel.getMin_order());
        // 是否自营
        goodsDetail.setIsSelfOperated(0);
        // 是否支持无库存下单
        goodsDetail.setIsOversold(0);
        // 商品官网链接
        goodsDetail.setGoodsUrl("");
        // 是否自行配送
        goodsDetail.setIsSelfDelivery("0");
        // 重量和
        // goodsDetail.setWeight(goodsModel.getWeight().toString());

        BsscGoodsDetailReq bsscGoodsDetailReq = new BsscGoodsDetailReq();
        bsscGoodsDetailReq.setGoods(Arrays.asList(goodsDetail));
        bsscGoodsDetailReq.setAccount("jzny");

        // 创建包装类
        BsscGoodsDetailWrap bsscGoodsDetailWrap = new BsscGoodsDetailWrap(bsscGoodsDetailReq);
        // 发起请求
        BsscGoodsDetailResp bsscGoodsPropertyResp = getBsscClient().execute(bsscGoodsDetailWrap);
        log.warn("详情变更-request:{}", bsscGoodsDetailWrap);
        log.warn("详情变更-response:{}", bsscGoodsPropertyResp);
        BsscResp bsscResp = new BsscResp();
        BeanUtils.copyProperties(bsscGoodsPropertyResp, bsscResp);
        return bsscResp;
    }

    @Override
    public List<BsscResp> orderAccept(final List<OrderAcceptModel> orderAcceptModel) {
        List<BsscOrderConfirmReq> bsscOrderConfirmReqList = new ArrayList<>();
        for (OrderAcceptModel acceptModel : orderAcceptModel) {
            BsscOrderConfirmReq req = new BsscOrderConfirmReq();
            BeanUtils.copyProperties(acceptModel, req);
            bsscOrderConfirmReqList.add(req);
        }
        return bsscClientOrders(bsscOrderConfirmReqList);
    }

    /**
     * 接单
     */
    public List<BsscResp> bsscClientOrders(List<BsscOrderConfirmReq> bsscOrderConfirmReqList) {
        List<BsscResp> bsscRespList = new ArrayList<>();
        for (BsscOrderConfirmReq req : bsscOrderConfirmReqList) {
            // 创建请求包装类
            BsscOrderConfirmWrap wrap = new BsscOrderConfirmWrap(req);
            BsscOrderConfirmResp resp = getBsscClient().execute(wrap);
            log.warn("bsscClientOrders-wrap:{},bsscClientOrders-resp:{}", wrap, resp);
            BsscResp bsscResp = new BsscResp();
            BeanUtils.copyProperties(resp, bsscResp);
            bsscRespList.add(bsscResp);
        }
        return bsscRespList;
    }

    @Override
    public BsscResp orderGoodsDeliver(final OrderGoodsDeliverModel orderGoodsDeliverModel) {
        BsscOrderDeliverReq req = new BsscOrderDeliverReq();
        BeanUtils.copyProperties(orderGoodsDeliverModel, req);
        return bsscClientShip(req);
    }

    /**
     * 发货
     *
     * @param req
     * @return
     */
    public BsscResp bsscClientShip(BsscOrderDeliverReq req) {
        // 创建请求包装类
        BsscOrderDeliverWrap wrap = new BsscOrderDeliverWrap(req);
        BsscOrderDeliverResp resp = getBsscClient().execute(wrap);
        log.warn("bsscClientShip-wrap:{},bsscClientShip-resp:{}", wrap, resp);
        // 发货单ID要存到发货记录，后面查询物流要通过这个id查询
        log.warn("发货单ID:{}", resp.getResult().getOutgoingCode());
        // 发货后调用妥投接口 ， 系统过段时间自动收货
        bsscClientProperVote(resp.getResult().getOutgoingCode());
        BsscResp bsscResp = new BsscResp();
        BeanUtils.copyProperties(resp, bsscResp);
        return bsscResp;
    }

    /**
     * 妥投 -- 发货后调用（发货后系统果断时间自动做收货操作）
     *
     * @return
     */
    public BsscResp bsscClientProperVote(String outgoingCode) {
        BsscOrderDeliveredNoticeReq req = new BsscOrderDeliveredNoticeReq();
        req.setOutgoingCode(outgoingCode);
        // 发货单来源：1：订单、2：售后
        req.setOutgoingSource("1");
        BsscOrderDeliveredNoticeWrap wrap = new BsscOrderDeliveredNoticeWrap(req);
        BsscOrderDeliveredNoticeResp resp = getBsscClient().execute(wrap);
        log.warn("bsscClientProperVote-wrap:{},bsscClientProperVote-resp:{}", wrap, resp);
        BsscResp bsscResp = new BsscResp();
        BeanUtils.copyProperties(resp, bsscResp);
        return bsscResp;
    }

    /**
     * 监听任务业务处理
     *
     * @param listenerModel
     */
    public BsscResp businessProcessing(ListenerModel listenerModel, Map<String, String> clientSecret) {
        // 供应商网络订单ID
        String orderNo = listenerModel.getContent().get("orderNo");
        log.warn("orderNo:{}", orderNo);
        // 供应商网络发货单号
        String outgoingCode = listenerModel.getContent().get("outgoingCode");
        log.warn("outgoingCode:{}", outgoingCode);
        String type = listenerModel.getType();
        String token = listenerModel.getAccessToken();
        JacksonJsonParser jsonParser = new JacksonJsonParser();
        String result = "0";
        String message = "";
        // 2001 新订单消息（预购单）-- 在固买下订单 ， 通过供应商网络订单号-调用getOrderDetail查询订单详情 ， 进行下单动作
        if (BsscListenerEnum.get(type).equals(BsscListenerEnum.Order)) {

            // 获取到订单详情构建下单Vo调用v1下单接口
            HttpHeaders headers = new HttpHeaders();
            headers.setContentType(MediaType.parseMediaType("application/json; charset=UTF-8"));
            headers.add("Accept", MediaType.ALL_VALUE);
            headers.add("Authorization", "Bearer " + token);

            HttpEntity<BsscOrderVo> httpEntity = new HttpEntity<>(BsscOrderVo.bsscOrderDetailRespToBsscOrderVo(bsscClientGetOrderDetail(orderNo)), headers);
//            HttpEntity<BsscOrderVo> httpEntity = new HttpEntity<>(BsscOrderVo.test(), headers);
            String orderResult = restTemplate.postForObject(AppUrl.getUrl(AppConst.ORDER_CENTER, "/OrderController/customerCreate"), httpEntity, String.class);
//            log.warn("/v1/order/customer/create--result:{}", orderResult);
            log.warn("/OrderController/customerCreate--result:{}", orderResult);
            Map<String, Object> map = jsonParser.parseMap(orderResult);
            Boolean code = (Boolean) map.get("success");
            String msg = map.get("errMessage").toString();

            if (code) {
                result = "1";
            } else {
                message = msg;
            }
        }
        // 2002 取消订单消息 {"id":"推送id","content" : {"orderNo" :"供应商网络订单号","cancelReason" :"取消原因"} ,"type": "2002", "time":"推送时间"}
        if (BsscListenerEnum.get(type).equals(BsscListenerEnum.cancelOrder)) {
            Map<String, String> params = new HashMap<>();
            params.put("clientOrderId", orderNo);

            HttpHeaders headers = new HttpHeaders();
            headers.setContentType(MediaType.APPLICATION_FORM_URLENCODED);
            headers.add("Accept", MediaType.ALL_VALUE);
            headers.add("Authorization", "Bearer " + token);
            HttpEntity<Map> httpEntity = new HttpEntity<>(params, headers);

            String url = AppUrl.getUrl(AppConst.ORDER_CENTER, "/OrderCustomerV1Service/customerOrderCancel");
            String orderResult = restTemplate.postForObject(url, httpEntity, String.class);
            log.warn("取消订单消息--result:{}", orderResult);
            Map<String, Object> map = jsonParser.parseMap(orderResult);
            String code = MapUtils.getString(map, "code");
            String msg = MapUtils.getString(map, "msg");

            if (code.equals("0")) {
                result = "1";
            }
            if (!code.equals("0")) {
                message = msg;
            }
        }
        // 2004 确认预购单 {"id":"推送id","content" : {"orderNo" :"供应商网络订单号"} ,"type": "2004", "time":"推送时间"}
        if (BsscListenerEnum.get(type).equals(BsscListenerEnum.ConfirmPreOrder)) {
            HttpHeaders headers = new HttpHeaders();
            headers.setContentType(MediaType.parseMediaType("application/json; charset=UTF-8"));
            headers.add("Accept", MediaType.ALL_VALUE);
            headers.add("Authorization", "Bearer " + token);

            MultiValueMap<String, String> params = new LinkedMultiValueMap<>();
            params.put("clientOrderId", Arrays.asList(orderNo));
            GatewayParam gatewayParam = new GatewayParam();
            gatewayParam.setQuery(MapUtil.of("params", params));
            HttpEntity<GatewayParam> httpEntity = new HttpEntity<>(gatewayParam, headers);

            String url = AppUrl.getUrl(AppConst.ORDER_CENTER, "/OrderCustomerV1Service/orderCustomerPayment");
            String orderResult = restTemplate.postForObject(url, httpEntity, String.class);
            log.warn("确认付款消息--result:{}", orderResult);
            Map<String, Object> map = jsonParser.parseMap(orderResult);
            String code = MapUtils.getString(map, "code");
            String msg = MapUtils.getString(map, "msg");

            if (code.equals("0")) {
                result = "1";
            }
            if (!code.equals("0")) {
                message = msg;
            }
        }
        // 2003 确认收货消息 -- 在固买收货 ， 根据供应商订单号查出对应固买的订单id和订单商品id
        if (BsscListenerEnum.get(type).equals(BsscListenerEnum.ConfirmReceipts)) {

            BsscOrderOutgoingResp resp = bsscClientGetOutGoing(orderNo);
            // 发货单列表
            OutgoingListEntity outgoing = resp.getResult().getOutgoingList().stream().filter(o -> o.getOutgoingCode().equals(outgoingCode)).findAny().orElse(null);
            // 封装调用收货接口vo
            BsscOrderReceivedVo bsscOrderReceivedVo = BsscOrderReceivedVo.builder().clientOrderId(orderNo).build();
            if (null != outgoing) {
                bsscOrderReceivedVo.setItemList(outgoing.getOutgoingGoods());
            }

            HttpHeaders headers = new HttpHeaders();
            headers.setContentType(MediaType.APPLICATION_JSON_UTF8);
            headers.add("Authorization", "Bearer " + token);

            HttpEntity<Object> httpEntity = new HttpEntity<>(bsscOrderReceivedVo, headers);

            String url = AppUrl.getUrl(AppConst.ORDER_CENTER, "/OrderCustomerV1Service/confirmByClientOrderGoods");

            String receiveResult = restTemplate.postForObject(url, httpEntity, String.class);
            log.warn("/v1/order/items/confirm-by-client-order-goods--result:{}", receiveResult);
            Map<String, Object> map = jsonParser.parseMap(receiveResult);
            String code = MapUtils.getString(map, "code");
            String msg = MapUtils.getString(map, "msg");

            if (code.equals("0")) {
                result = "1";
            }
            if (!code.equals("0")) {
                message = msg;
            }
        }
        // 拒绝售后
        if (BsscListenerEnum.get(type).equals(BsscListenerEnum.ApplyForAfterSales)) {
            String afterSaleNo = listenerModel.getContent().get("afterSaleNo");
            BsscAfterSaleRejectReq req = new BsscAfterSaleRejectReq();
            // 供应商网络售后单号
            req.setAfterSaleNo(afterSaleNo);
            // 随机8位
            String mallAfterSaleNo = StringUtils.randomStr8();
            // 电商系统售后单号
            req.setMallAfterSaleNo(mallAfterSaleNo);
            // 拒单原因
            req.setRejectReason("线上售后暂未开放！！！");
            BsscAfterSaleRejectResp bsscAfterSaleRejectResp = bsscClientApplyForAfterSales(req);
            result = bsscAfterSaleRejectResp.getResult().getResult().toString();
        }
        Map<String, String> map = new HashMap<>(1);
        map.put("result", result);
        map.put("message", message);
        // 返回信息包装成bssc编码加密返回
        String rspJsonData = JsonUtils.toJsonNoCode(map);
        String respData = Base64.encode(rspJsonData);
        BsscResp bsscResp = new BsscResp("0", "调用成功", respData, null);
        byte[] signReq = SignatureUtils.sign(JSON.toJSONString(bsscResp), clientSecret.get(PRIVATE_KEY));
        String sign = Base64.encode(signReq);
        bsscResp.setSign(sign);
        return bsscResp;
    }

    /**
     * 拒绝售后
     *
     * @param req
     * @return
     */
    public BsscAfterSaleRejectResp bsscClientApplyForAfterSales(BsscAfterSaleRejectReq req) {
        BsscAfterSaleRejectWrap wrap = new BsscAfterSaleRejectWrap(req);
        BsscAfterSaleRejectResp resp = getBsscClient().execute(wrap);
        log.warn("BsscAfterSaleRejectResp-wrap:{},BsscAfterSaleRejectResp-resp:{}", wrap, resp);
        return resp;
    }

    /**
     * 查询发货单
     *
     * @param orderNo 供应商网络订单号
     * @return 发货单详情（包含固买商品ID）
     */
    public BsscOrderOutgoingResp bsscClientGetOutGoing(String orderNo) {
        // 创建请求对象
        BsscOrderOutgoingReq req = new BsscOrderOutgoingReq();
        // 供应商订单号
        req.setOrderNo(orderNo);
        // 创建请求类
        BsscOrderOutgoingWrap wrap = new BsscOrderOutgoingWrap(req);

        // 发起请求
        BsscOrderOutgoingResp resp = getBsscClient().execute(wrap);
        log.warn("bsscClientGetOutGoing-wrap:{},bsscClientGetOutGoing-resp:{}", wrap, resp);
        return resp;
    }

    /**
     * 查询订单详情
     *
     * @param orderNo 供应商网络订单号（冀中订单号）
     * @return 订单详情（冀中订单详情）
     */
    public BsscOrderDetailResp bsscClientGetOrderDetail(String orderNo) {
        //创建请求对象
        BsscOrderDetailReq req = new BsscOrderDetailReq();
        // 供应商网络订单号
        req.setOrderNo(orderNo);
        //创建请求包装类
        BsscOrderDetailWrap wrap = new BsscOrderDetailWrap(req);

        //发起请求
        BsscOrderDetailResp resp = getBsscClient().execute(wrap);
        log.warn("bsscClientGetOrderDetail-wrap:{},bsscClientGetOrderDetail-resp:{}", wrap, resp);
        return resp;
    }

    /**
     * 获取冀中客户sercret
     *
     * @return
     */
    private Map<String, String> getClientSecret() {
        OutApiClientDto outapi = OutApiClientApiUtils.getByGomroUsername("punchout_bssc");

        if (outapi == null) {
            throw new BizException("账户不存在");
        }

        try {
            log.info("\n>>>>>>>>>>>>>>>>>>>>>冀中secretInfo:{}\n", outapi.getExtends_attr());
            return objectMapper.readValue(outapi.getExtends_attr(), Map.class);
        } catch (Exception e) {
            throw new BizException("冀中电商对接秘钥JSON字符串转换失败");
        }
    }

    @SneakyThrows
    private BsscClient getBsscClient() {
        OutApiClientDto punchoutBssc = OutApiClientApiUtils.getByGomroUsername("punchout_bssc");


        Map<String, String> clientSecret = objectMapper.readValue(punchoutBssc.getExtends_attr(), Map.class);
        // 定义公共参数
        BsscClientParams clientParams = new BsscClientParams();
        // 请求地址 http://58.22.61.222:46791/standard
        clientParams.setBaseUrl(punchoutBssc.getResource_url());
        // 开发者ID KFZEMwpIRg5
        clientParams.setClientId(punchoutBssc.getClient_id());
        // 开发者私钥 MIGTAgEAMBMGByqGSM49AgEGCCqBHM9VAYItBHkwdwIBAQQgCbWjjYMl5WLC7H/8dlmR8jlS9GrRoUH2aP+V1WgG4/mgCgYIKoEcz1UBgi2hRANCAAQ+9fFL0ncdFJN0bIqccZ3HLKc+rhytYSCoDCZWpMuNYy+ryd4Z/LWUrrUWHkAKtqpDDrUD1B4MeKyg+3/cg0ZK
        clientParams.setPrivateKeyStr(clientSecret.get(PRIVATE_KEY));
        // 开发者公钥 MFkwEwYHKoZIzj0CAQYIKoEcz1UBgi0DQgAEPvXxS9J3HRSTdGyKnHGdxyynPq4crWEgqAwmVqTLjWMvq8neGfy1lK61Fh5ACraqQw61A9QeDHisoPt/3INGSg==
        clientParams.setPublicKeyStr(clientSecret.get(PUBLIC_EC_KEY));
        // 创建实例
        return new BsscClient(clientParams);
    }

    /**
     * 获取token值
     *
     * @param req
     * @return
     */
    @SneakyThrows
    public String getToken(BsscReq<String> req) {
        log.warn("req.getData():{}", req.getData());
        BsscDataReq dataReq = objectMapper.readValue(req.getData(), BsscDataReq.class);

        String host = AppUrl.getAppHost("app-gateway");

        String url = String.format("%s/api/authorization/login/password/test?username=%s&password=%s&client_id=api", host, dataReq.getUsername(), dataReq.getPassword());

        log.info(">>>>>>>>>>>>>>>>>url={}", url);

        SingleResponse<Map<String, Object>> response = restTemplate.getForObject(url, SingleResponse.class);
        if (!response.isSuccess()) {
            return null;
        }

        return JSON.toJSONString(Optional.ofNullable(response.getData()).orElseThrow(() -> new BizException("获取token 失败")));
    }

    /**
     * 检查token有效
     *
     * @param accessToken
     */
    public void checkToken(String accessToken) {
        //验证功能在前置网关里处理了
//        HttpHeaders headers = new HttpHeaders();
//        headers.add("Authorization", "bearer " + accessToken);
//        RestTemplate restTemplate = new RestTemplate();
//        String result = restTemplate.postForObject("http://passport/user", new HttpEntity<String>(headers), String.class);
//        log.info("result: {}", result);
    }

    public static class BsscServiceBuilder {
        private static final BsscServiceImpl instance = new BsscServiceImpl();
    }
}
